package com.example.huichaoliu;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.huichaoliu.adapters.ProductAdapter;
import com.huichaoliu.app.R;
import com.huichaoliu.data.Config;
import com.huichaoliu.data.UserInfo;
import com.rederxu.request.HTTPRequest;
import com.rederxu.request.onRequestOverListener;
import com.rederxu.tools.StringUtils;
import com.source.utils.Utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MallFragment extends Fragment implements OnItemClickListener,OnClickListener,OnScrollListener {

	private View v = null;
	private GridView gridView = null;
	private TextView tv_suit = null;
	private TextView tv_pants = null;
	private TextView tv_jacket = null;
	private TextView tv_shoes = null;
	private ImageView ic_style_selected = null;
	private ImageView ic_season_selected = null;
	private ImageView ic_price_selected = null;
	private TextView tv_type_price = null;
	private TextView tv_type_style = null;
	private TextView tv_type_season = null;
	private View layout_items = null;
	private TextView tv_item1 = null;
	private TextView tv_item2 = null;
	private TextView tv_item3 = null;
	private TextView tv_item4 = null;
	private TextView tv_item5 = null;
	private TextView tv_item6 = null;
	public static final int CODE_BACK_FROM_DETAIL = 1001;
	private JSONArray jaStylist = new JSONArray();
	private JSONArray jaGoodsData = new JSONArray();
	private JSONArray jaGoodsNow = new JSONArray();
	private TextView[] tv_items = null;
	private int selectedPrice = 0;
	private int selectedSeason = 0;
	private int selectedStyle = 0;
	private int typeSelected = 0;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(v == null){
			v = inflater.inflate(R.layout.fragment_mall, null);
			init();
			initData();
		}
		ViewGroup parent = (ViewGroup) v.getParent();
		if (parent != null) {
			parent.removeView(v);
		}
		return v;
	}
	
	private void init(){
		gridView = (GridView) v.findViewById(R.id.gridView);
		gridView.setOnItemClickListener(this);
		gridView.setOnScrollListener(this);
		tv_suit = (TextView)v.findViewById(R.id.tv_suit);
		tv_jacket = (TextView)v.findViewById(R.id.tv_jacket);
		tv_pants = (TextView)v.findViewById(R.id.tv_pants);
		tv_shoes = (TextView)v.findViewById(R.id.tv_shoes);
		tv_type_price = (TextView)v.findViewById(R.id.tv_type_price);
		tv_type_style = (TextView)v.findViewById(R.id.tv_type_style);
		tv_type_season = (TextView)v.findViewById(R.id.tv_type_season);
		ic_style_selected = (ImageView) v.findViewById(R.id.ic_selected_style);
		ic_price_selected = (ImageView) v.findViewById(R.id.ic_selected_price);
		ic_season_selected = (ImageView) v.findViewById(R.id.ic_selected_season);
		layout_items = v.findViewById(R.id.layout_items);
		tv_item1 = (TextView) v.findViewById(R.id.tv_item1);
		tv_item2 = (TextView) v.findViewById(R.id.tv_item2);
		tv_item3 = (TextView) v.findViewById(R.id.tv_item3);
		tv_item4 = (TextView) v.findViewById(R.id.tv_item4);
		tv_item5 = (TextView) v.findViewById(R.id.tv_item5);
		tv_item6 = (TextView) v.findViewById(R.id.tv_item6);
		TextView[] tv_item_inited = {tv_item1,tv_item2,tv_item3,tv_item4,tv_item5,tv_item6};
		tv_items = tv_item_inited;
		tv_suit.setOnClickListener(this);
		tv_jacket.setOnClickListener(this);
		tv_pants.setOnClickListener(this);
		tv_shoes.setOnClickListener(this);
		tv_type_price.setOnClickListener(this);
		tv_type_style.setOnClickListener(this);
		tv_type_season.setOnClickListener(this);
		tv_item1.setOnClickListener(this);
		tv_item2.setOnClickListener(this);
		tv_item3.setOnClickListener(this);
		tv_item4.setOnClickListener(this);
		tv_item5.setOnClickListener(this);
		tv_item6.setOnClickListener(this);
	}

	private void initData(){
		try{
			Bundle bundle = new Bundle();
			UserInfo info = new UserInfo(getActivity());
			JSONObject jo = new JSONObject();
			if(info.getUid() != null){
				jo.put("userId", info.getUid());
				bundle.putString("request", Utils.requestParamsEncode(jo));
			}else{
				jo.put("userId", "");
				bundle.putString("request", Utils.requestParamsEncode(jo));
			}
			HTTPRequest.POST(getActivity(), Config.REQUEST_URLS.URL_COMMODITY_LIST, bundle, new onRequestOverListener() {
				
				@Override
				public void onRequestOver(String result) {
					try{
						JSONObject jo = new JSONObject(result);
						if(jo.getInt("code") != 0){
							Toast.makeText(getActivity(), jo.getString("message"), 1).show();
							return;
						}
						jaGoodsData = jo.getJSONArray("response");
						jaGoodsNow = jaGoodsData;
						gridView.setAdapter(new ProductAdapter(getActivity(),jaGoodsNow));
					}catch(JSONException e){
						if(result.contains("500")){
							try{
								JSONObject jo = new JSONObject(result);
								Toast.makeText(getActivity(), jo.getString("message"), 1).show();
							}catch(JSONException e2){
								
							}
						}
						e.printStackTrace();
					}
				}
			});

			HTTPRequest.POST(getActivity(), Config.REQUEST_URLS.URL_COMMODITY_STYLE_LIST, bundle, new onRequestOverListener() {
				@Override
				public void onRequestOver(String result) {
					try{
						JSONObject jo = new JSONObject(result);
						if(jo.getInt("code") != 0){
							Toast.makeText(getActivity(), jo.getString("message"), Toast.LENGTH_SHORT).show();
							return;
						}
						jaStylist = jo.getJSONArray("response");
					}catch(JSONException e){
						e.printStackTrace();
					}
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		layout_items.setVisibility(View.INVISIBLE);
		String url = ((ProductAdapter)gridView.getAdapter()).getUrl(position);
		String code = ((ProductAdapter)gridView.getAdapter()).getCode(position);
		String name = ((ProductAdapter)gridView.getAdapter()).getName(position);
		String cover = ((ProductAdapter)gridView.getAdapter()).getCover(position);
		if(url == null || StringUtils.isBlank(url)){
			Toast.makeText(getActivity(), "获取商品详情地址失败", Toast.LENGTH_SHORT).show();
			return;
		}
		Intent i = new Intent(getActivity(),DetailGoodsActivity.class);
		i.putExtra("url", url);
		i.putExtra("code", code);
		i.putExtra("name", name);
		i.putExtra("cover", cover);
		startActivityForResult(i, CODE_BACK_FROM_DETAIL);
	}

	@Override
	public void onClick(View v) {
		layout_items.setVisibility(View.INVISIBLE);
		switch(v.getId()){
		case R.id.tv_suit:
			tv_suit.setBackgroundColor(Color.BLACK);
			tv_jacket.setBackgroundColor(Color.TRANSPARENT);
			tv_pants.setBackgroundColor(Color.TRANSPARENT);
			tv_shoes.setBackgroundColor(Color.TRANSPARENT);
			break;
		case R.id.tv_pants:
			tv_suit.setBackgroundColor(Color.TRANSPARENT);
			tv_jacket.setBackgroundColor(Color.TRANSPARENT);
			tv_pants.setBackgroundColor(Color.BLACK);
			tv_shoes.setBackgroundColor(Color.TRANSPARENT);
			break;
		case R.id.tv_jacket:
			tv_suit.setBackgroundColor(Color.TRANSPARENT);
			tv_jacket.setBackgroundColor(Color.BLACK);
			tv_pants.setBackgroundColor(Color.TRANSPARENT);
			tv_shoes.setBackgroundColor(Color.TRANSPARENT);
			break;
		case R.id.tv_shoes:
			tv_suit.setBackgroundColor(Color.TRANSPARENT);
			tv_jacket.setBackgroundColor(Color.TRANSPARENT);
			tv_pants.setBackgroundColor(Color.TRANSPARENT);
			tv_shoes.setBackgroundColor(Color.BLACK);
			break;
		case R.id.tv_type_price:
			typeSelected = 0;
			ic_price_selected.setVisibility(View.VISIBLE);
			ic_style_selected.setVisibility(View.GONE);
			ic_season_selected.setVisibility(View.GONE);
			layout_items.setVisibility(View.VISIBLE);
			tv_item1.setText("全部");
			tv_item2.setText("300-500");
			tv_item3.setText("0-100");
			tv_item4.setText("500-1000");
			tv_item5.setText("100-300");
			tv_item6.setText("1000以上");
			for(int i = 0; i < tv_items.length;i++){
				if(selectedPrice == i){
					tv_items[i].setBackgroundColor(0x886A6A6A);
				}else{
					tv_items[i].setBackgroundColor(0x6A6A6A);
				}
			}
			break;
		case R.id.tv_type_season:
			typeSelected = 1;
			ic_price_selected.setVisibility(View.GONE);
			ic_style_selected.setVisibility(View.GONE);
			ic_season_selected.setVisibility(View.VISIBLE);
			layout_items.setVisibility(View.VISIBLE);
			tv_item1.setText("全部");
			tv_item3.setText("春季");
			tv_item5.setText("夏季");
			tv_item2.setText("秋季");
			tv_item4.setText("冬季");
			tv_item6.setText("");
			for(int i = 0; i < tv_items.length;i++){
				if(selectedSeason == i){
					tv_items[i].setBackgroundColor(0x886A6A6A);
				}else{
					tv_items[i].setBackgroundColor(0x6A6A6A);
				}
			}
			break;
		case R.id.tv_type_style:
			typeSelected = 2;
			ic_price_selected.setVisibility(View.GONE);
			ic_style_selected.setVisibility(View.VISIBLE);
			ic_season_selected.setVisibility(View.GONE);
			layout_items.setVisibility(View.VISIBLE);
			if(jaStylist == null){
				Toast.makeText(getActivity(), "获取相关数据中...", Toast.LENGTH_SHORT).show();
				return;
			}
			tv_item1.setText("全部");
			tv_item1.setTag(0);
			tv_item2.setText("");
			tv_item3.setText("");
			tv_item4.setText("");
			tv_item5.setText("");
			tv_item6.setText("");
			try{
				for(int i = 0; i < jaStylist.length() && i < tv_items.length - 1;i++){
					JSONObject jo = jaStylist.getJSONObject(i);
					tv_items[i + 1].setText(jo.getString("name"));
					tv_items[i + 1].setTag(jo.getInt("styleId"));
				}
			}catch(JSONException e){
				e.printStackTrace();
			}
			for(int i = 0; i < tv_items.length;i++){
				if(selectedStyle == i){
					tv_items[i].setBackgroundColor(0x886A6A6A);
				}else{
					tv_items[i].setBackgroundColor(0x6A6A6A);
				}
			}
			break;
		case R.id.tv_item1:
			setChoice(0);
			break;
		case R.id.tv_item2:
			setChoice(1);
			break;
		case R.id.tv_item3:
			setChoice(2);
			break;
		case R.id.tv_item4:
			setChoice(3);
			break;
		case R.id.tv_item5:;
			setChoice(4);
			break;
		case R.id.tv_item6:
			setChoice(5);
			break;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(layout_items != null && layout_items.getVisibility() == View.VISIBLE){
			layout_items.setVisibility(View.GONE);
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == CODE_BACK_FROM_DETAIL && resultCode == Activity.RESULT_OK){
			((HomeActivity)getActivity()).setViewPagerPosition(1);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void setChoice(int position){
		if(tv_items[position].getText().toString().equalsIgnoreCase("")){
			return;
		}
		if(typeSelected == 0){
			selectedPrice = position;
			tv_type_price.performClick();
		}else if(typeSelected == 1){
			selectedSeason = position;
			tv_type_season.performClick();
		}else if(typeSelected == 2){
			selectedStyle = position;
			tv_type_style.performClick();
		}
		layout_items.setVisibility(View.GONE);
		//筛选数据
		//price
		if(selectedPrice == 0 && selectedSeason == 0 && selectedStyle == 0){
			jaGoodsNow = jaGoodsData;
			gridView.setAdapter(new ProductAdapter(getActivity(),jaGoodsNow));
			return;
		}
		jaGoodsNow = new JSONArray();
		try {
			for(int i = 0;i < jaGoodsData.length();i++){
				JSONObject jo = jaGoodsData.getJSONObject(i);
				if(selectedPrice != 0){
					long price = jo.getLong("price");
					long max = 100000;
					long min = 0;
					if(selectedPrice == 1){
						max = 500;
						min = 300;
					}else if(selectedPrice == 2){
						max = 100;
						min = 0;
					}else if(selectedPrice == 3){
						min = 500;
						max = 1000;
					}else if(selectedPrice == 4){
						min = 100;
						max = 300;
					}else {
						min = 1000;
						max = 200000;
					}
					if(price < min || price > max){
						continue;
					}
				}
				if(selectedSeason != 0){
					int type = jo.getInt("season");
					if(type != selectedSeason){
						continue;
					}
				}
				if(selectedStyle != 0){
					int style = (Integer) tv_items[selectedStyle - 1].getTag();
					if(style != jo.getInt("style")){
						continue;
					}
				}
				jaGoodsNow.put(jo);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		gridView.setAdapter(new ProductAdapter(getActivity(),jaGoodsNow));
	}
}
